package com.example.ddcoursequery;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.app.model.Teacher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2015/12/14.
 */
public class AppStartActivity extends Activity {
    private static final String TAG_SPLASH_SCREEN = "splashScreen";
    private SplashScreenFragment mSplashScreenFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        final FragmentManager fm = getFragmentManager();


        mSplashScreenFragment = (SplashScreenFragment) fm.findFragmentByTag(TAG_SPLASH_SCREEN);
        if (mSplashScreenFragment == null) {
            mSplashScreenFragment = new SplashScreenFragment();
            fm.beginTransaction().add(android.R.id.content, mSplashScreenFragment, TAG_SPLASH_SCREEN).commit();
        }
        LoadingTask mTask = new LoadingTask();
        mTask.execute();
    }

    /**
     * 异步加载数据类
     */
    private class LoadingTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            CacheTeacher.teacherList = new ArrayList<AppTeacher>();
            CacheTeacher.courseList = new ArrayList<List<AppCourse>>();
            CacheTeacher.titleList = new ArrayList<String>();
            boolean flag = getTeacherListFromDB();
            if(!flag){
                Log.i("lyj", "get from http");
                getTeacherListFromHttp();
                //通知service将数据存储到本地数据库
                Intent intent = new Intent(getApplicationContext(),InitStoreTeacherService.class);
                startService(intent);

            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(AppStartActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private boolean getTeacherListFromDB() {
        MyDbHelper myDbHelper = new MyDbHelper(getApplicationContext(), "courses.db", null, Resources.db_version);
        DBData dbData = new DBData(myDbHelper);
        boolean flag = dbData.getAllTeachers();
        return flag;
    }

    private void getTeacherListFromHttp(){
        HttpData httpData = new HttpData();
        httpData.getTeacherList();
    }
}
